package com.rub.android.jetpack.viewmodel

import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.rub.android.dto.JsonResult
import com.rub.android.jetpack.model.Repo
import com.rub.android.service.GitHubService
import kotlinx.coroutines.flow.Flow

class GithubViewModel(private val repository: GitHubService) : ViewModel() {

    //请求参数
    private var requestData = MutableLiveData<RequestParam>()

    val responseData = Transformations.switchMap(requestData) {
        liveData {
            val result = try {
                val ret = repository.refreshSearch(it.prePage,it.page,it.keyWord)
                Result.success(ret)
            } catch (e: Exception) {
                Result.failure<JsonResult>(e)
            }
            emit(result)
        }
    }


    /**
     * 获取数据
     */
    fun getPagingData(keyword:String): Flow<PagingData<Repo>> {
        return repository.getPagingData(keyword).cachedIn(viewModelScope)
    }
    /**
     * 实现
     */
    fun search(prePage: Int,page: Int,keyWord:String) {
        requestData.value = RequestParam(prePage,page,keyWord)
    }


    /**
     * 内练类
     */
    inner class RequestParam(val prePage: Int, val page: Int,val keyWord:String)

}